﻿using System.Data;
using System.Data.OleDb;

namespace ConsoleApp3;

public class ExcellConnection
{
    private OleDbConnection _dbConnection;
    public ExcellConnection(string filePath)
    {
        FileInfo file = new(filePath);
        if (!file.Exists)
        {
            throw new Exception("文件不存在");
        }
        string ConnectionString = $"Provider=Microsoft.ACE.OLEDB.12.0;Data Source={filePath};Extended Properties='Excel 12.0;HDR=no;IMEX=1;'";
        _dbConnection = new(ConnectionString);
        _dbConnection.Open();
    }
    public Task<string> GetFileName(string fileId)
    {
        return Task.Run(() =>
        {
            OleDbCommand cmd = new($"select F4,F6 from [sheet1$] where F1 ='{fileId}';", _dbConnection);
            OleDbDataAdapter apt = new(cmd);
            DataTable dt = new();
            apt.Fill(dt);
            dt.TableName = "table1";
            var dr = dt.Rows[0];
            var extension = dr[0].ToString();
            var fileName = dr[1].ToString();
            return $"{fileName}.{extension}";
        });

    }
    public async Task CopyFileAsync(string path, string fileId, string destPpath)
    {
        var fileName = await GetFileName(fileId);
        var p1 = Path.Combine(path, fileId);
        var p2 = Path.Combine(destPpath, fileName);
        //File.Copy(p1, p2);
        using (FileStream sourceStream = File.Open(p1, FileMode.Open))
        {
            using (FileStream destinationStream = File.Create(p2))
            {
                await sourceStream.CopyToAsync(destinationStream);
            }
        }
    }
}

public static class BinarySearchUtils
{
    public static Int32 BinarySearchIndexOf<T>(this IList<T> list, T value, IComparer<T>? comparer = null)
    {
        if (list == null)
            throw new ArgumentNullException(nameof(list));

        comparer ??= Comparer<T>.Default;

        Int32 lower = 0;
        Int32 upper = list.Count - 1;

        while (lower <= upper)
        {
            Int32 middle = lower + (upper - lower) / 2;
            Int32 comparisonResult = comparer.Compare(value, list[middle]);
            if (comparisonResult == 0)
                return middle;
            else if (comparisonResult < 0)
                upper = middle - 1;
            else
                lower = middle + 1;
        }

        return ~lower;
    }
}